<?php


namespace app\api\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class User
{
    public $userObj = null;

    public function __construct()
    {
        $this->userObj = new UserModel();
    }

    public function login($data){
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']){
            throw new Exception('不存在该验证码',-1009);
        }
        // 需要去判断表是否有用户记录    phone_number
        // 生成token

        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (!$user){
            // 用户不存在 新增
            $username ="粉-".$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal')
            ];
            try {
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
            }catch (\Exception $e){
                throw new Exception('数据库内部异常');
            }
        }else{
            // 用户存在 更新
            $userId = $user->id;
            $username = $user->username;
        }
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id' => $userId,
            'username' => $username
        ];
        $res = cache(config('redis.token_pre').$token,$redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['token' => $token, "username" => $username] : false;
    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getNormalUserById($id){
        $user = $this->userObj->getUserById($id);
        if (!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return  $user->toArray();
    }

    /**
     * 返回正常用户
     * @param $username
     * @return array
     */
    public function getNormaUserByUsername($username){
        $user = $this->userObj->getUserByUsername($username);
        if (!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return  $user->toArray();
    }

    public function update($id,$data){
        $user = $this->getNormalUserById($id);
        if (!$user){
            throw new Exception('不存在该用户');
        }
        // 检查用户是否存在
        $userResult = $this->getNormaUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id){
            throw new Exception('该用户已存在,该户已存在请重新设置');
        }
        return $this->userObj->updateByID($id,$data);
    }

}